package com.flute.icrawler.app.processor.extractor.special;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.app.processor.extractor.ExtractorBelongings;
import com.flute.icrawler.config.CrawlConfigUtil;
import com.flute.icrawler.config.ExtractorBelongingsAlgo;

public class ExtractorBelongingsAlgoFactory {

	private Map<String, IExtractorBelongingsAlgo> hmPattenToAlgo = new HashMap<String, IExtractorBelongingsAlgo>();

	private static ExtractorBelongingsAlgoFactory algoFactory = null;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ExtractorBelongings.class);

	private ExtractorBelongingsAlgoFactory() {
		List<ExtractorBelongingsAlgo> extractorBelongingsAlgos = CrawlConfigUtil
				.getBaseConfig().getExtractorBelongingsAlgos();

		for (int i = 0; i < extractorBelongingsAlgos.size(); i++) {
			try {
				hmPattenToAlgo.put(extractorBelongingsAlgos.get(i).getPatten(),
						((IExtractorBelongingsAlgo) Class.forName(
								extractorBelongingsAlgos.get(i).getAlgo()
										.replaceAll("\r\n", "").trim())
								.newInstance()));
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				LOGGER.error("", e);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				LOGGER.error("", e);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				LOGGER.error("", e);
			}
		}

		// hmPattenToAlgo.put("http://v.youku.com/v_show/id_.*\\.html",
		// YOU_KU_COMMENT_ALGO);
	}

	public static ExtractorBelongingsAlgoFactory getInstance() {
		if (null == algoFactory) {
			algoFactory = new ExtractorBelongingsAlgoFactory();
		}
		return algoFactory;
	}

	public IExtractorBelongingsAlgo getAlgo(String url) {

		Iterator<String> iterator = hmPattenToAlgo.keySet().iterator();
		while (iterator.hasNext()) {
			String regEx = iterator.next();
			Pattern p = Pattern.compile(regEx);
			Matcher matcher = p.matcher(url);
			if (matcher.find()) {
				return hmPattenToAlgo.get(regEx);
			}
		}
		return null;

	}

	public static void main(String[] args) {
		IExtractorBelongingsAlgo algo = ExtractorBelongingsAlgoFactory
				.getInstance().getAlgo(
						"http://u.youku.com/user_show/id_UMjkzOTM4NjUy.html");
		// http://u.youku.com/user_show/id_UMjkzOTM4NjUy.html
		System.out.println(algo);

	}
}
